<!DOCTYPE html>
<html lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
    <meta content="telephone=no" name="format-detection"/>
	<title>canvas优化图片加载</title>
	<style>
		.test {
			width:400px;
			height: 300px;
			border: 1px solid #ccc;
			margin: 10px auto 0;
			float: left;
			position: relative;
		}
		.test img {
			width: 100%;
			height: 100%;
		}
		.zc_canvas {
			position: absolute;
			/*width: 100%;
			height: 100%;*/
		}
	</style>
</head>
<body>
	<div class="test"><canvas width="400" height="300" class="zc_canvas" data-src="./img/1.jpg"></canvas></div>
	<div class="test"><canvas width="400" height="300" class="zc_canvas" data-src="./img/2.jpg"></canvas></div>
	<div class="test"><canvas width="400" height="300" class="zc_canvas" data-src="./img/3.jpg"></canvas></div>
	<div class="test"><canvas width="400" height="300" class="zc_canvas" data-src="./img/4.jpg"></canvas></div>
	<div class="test"><canvas width="400" height="300" class="zc_canvas" data-src="./img/5.jpg"></canvas></div>
	<div class="test"><canvas width="400" height="300" class="zc_canvas" data-src="./img/6.jpg"></canvas></div>
	<div class="test"><canvas width="400" height="300" class="zc_canvas" data-src="./img/7.jpg"></canvas></div>
	<div class="test"><canvas width="400" height="300" class="zc_canvas" data-src="./img/8.jpg"></canvas></div>
	<div class="wrap">	
		<div class="test"><img src="./img/1.jpg"></div>
		<div class="test"><img src="./img/2.jpg"></div>
		<div class="test"><img src="./img/3.jpg"></div>
		<div class="test"><img src="./img/4.jpg"></div>
		<div class="test"><img src="./img/5.jpg"></div>
		<div class="test"><img src="./img/6.jpg"></div>
		<div class="test"><img src="./img/7.jpg"></div>
		<div class="test"><img src="./img/8.jpg"></div>
	</div>






	<script>
		window.onload=function() {
			function renderImgByCanvas(canvas_dom) {
				var img=new Image();
				img.src=canvas_dom.getAttribute('data-src');
				img.onload = function() {
					var ctx=canvas_dom.getContext("2d");
					ctx.drawImage(img,0,0,400,300);
				}
			}
			function renderImg() {
				var allCans = document.getElementsByTagName('canvas');
				for(var i=0;i<allCans.length;i++) {
					renderImgByCanvas(allCans[i]);
				}
			}
			renderImg();
		}

		/*

			1、必须给canvas宽高具体值，不能百分比

			2、drawImage(img,0,0,400,300)方法参数里，只能是具体值，不能是百分比

		*/
	</script>
</body>
</html>